//
//  XQKeychainService.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/29.
//

#import "XQKeychainService.h"

@implementation XQKeychainService

+ (BOOL)saveToKeychainData:(NSString *)data {
    NSData *dataToStore = [data dataUsingEncoding:NSUTF8StringEncoding];
    
    // 创建查询字典
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: @"com.joinPeso.service",
        (__bridge id)kSecValueData: dataToStore
    };
    
    // 删除旧数据（如果存在）
    SecItemDelete((__bridge CFDictionaryRef)query);
    
    // 添加新数据
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
    
    return (status == errSecSuccess);
}

+ (NSString *)loadFromKeychain {
    // 创建查询字典
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: @"com.joinPeso.service",
        (__bridge id)kSecReturnData: @YES,
        (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne
    };
    
    CFTypeRef result = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
    
    if (status == errSecSuccess) {
        NSData *data = (__bridge_transfer NSData *)result;
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    
    return nil;
}

@end
